package org.alvin.i18n;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import org.alvin.i18n.ui.Pinyin4jUtil;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SpringBootI18nTest {

    public static void main(String[] args) throws IOException {
        Path dir = Paths.get("D:\\tangzhichao\\workspace\\dev_invoice_20231107\\electrombile\\xiaolancharging");
        StringBuilder builder = new StringBuilder();
        Map<String, String> dict = Maps.newHashMap();
        Properties properties = new Properties();
        String dictPath = "D:\\tangzhichao\\workspace\\dev_invoice_20231107\\electrombile\\xiaolancharging\\common\\src\\main\\resources\\i18n\\i18n_zh.txt";
        properties.load(new InputStreamReader(Files.newInputStream(Paths.get(dictPath)), "UTF-8"));
        properties.forEach((k, v) -> {
            dict.put(k.toString(), v.toString());
        });

        Files.list(dir).forEach(item -> {
            if (Files.exists(item.resolve("pom.xml"))) {
                Path path = item.resolve("src").resolve("main");
                List<File> javaFiles = findChinese(path.resolve("java").toFile(), "//.*|/\\*.*?\\*/", ".java");
                toTrim(javaFiles, builder, dict);
//                findChinese(path.resolve("resources").toFile(), "<!--.*?-->", ".xml").forEach(item1 ->{
//                    if(item1.getName().endsWith("Mapper.xml")){
//                        System.out.println(item1.getAbsolutePath());
//                    }
//                });
            }
        });
        Files.write(Paths.get("D:", "xli18n.txt"), builder.toString().getBytes());
//        properties.list(new PrintWriter(new FileOutputStream(new File("D:/xli18n.txt"))));

//        File file = new File("D:\\tangzhichao\\workspace\\dev_invoice_20231107\\electrombile\\xiaolancharging\\centerserver\\src\\main\\java\\com\\xl\\centerserver\\system\\acl\\user\\UserController.java");
//
//        toTrim(Lists.newArrayList(file), builder, dict);
//        System.out.println(builder);
    }

    private static void toTrim(List<File> javaFiles, StringBuilder sb, Map<String, String> dict) {
        //深度去注解，找到中文部分
        for (File f : javaFiles) {
            try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
                StringBuilder content = new StringBuilder();
                reader.lines().forEach(content::append);
                String content1 = content.toString().replaceAll("@[\\w\\.]+(\\(.*?\\))?", "");
                content1 = content1.replaceAll("//.*|/\\*.*?\\*/", "");
                content1 = content1.replaceAll("(log|logger|StaticLog)\\.(info|debug|warn|error)\\(.*?\\);", "");
                content1 = content1.replaceAll("System\\.out\\.(println|print|printf)\\(.*?\\);", "");
                Pattern pattern = Pattern.compile("\"([^\"]*[\u4e00-\u9fa5]+[^\"]*)\"");
                Matcher matcher = pattern.matcher(content1);

                String distContent = new String(Files.readAllBytes(f.toPath()));
                boolean flag = false;
                while (matcher.find()) {
                    flag = true;
                    System.out.println(f.getAbsolutePath());
                    String text = matcher.group(1);
                    System.out.println(text);
                    String pyKey = Pinyin4jUtil.textToHanYuPinyin(text, HanyuPinyinCaseType.LOWERCASE, HanyuPinyinToneType.WITHOUT_TONE,
                            HanyuPinyinVCharType.WITH_U_AND_COLON);
                    pyKey = pyKey.replaceAll("\\W", "");
                    if (dict.containsKey(pyKey)) {
                        continue;
                    }
                    dict.put(pyKey, text);
                    sb.append(pyKey).append("=").append(text).append("\n");
                    distContent = distContent.replace("\"" + text + "\"", "com.xl.i18n.I18nUtils.getString(\"" + pyKey + "\")");
                }
                if (flag) {
                    System.out.println(f);
                }
                Files.write(f.toPath(), distContent.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            //
        }

    }


    private static List<File> findChinese(File file, String comment, String fileType) {
        LinkedList<File> files = new LinkedList<>();
        files.add(file);
        List<File> resultFiles = Lists.newArrayList();
        while (!files.isEmpty()) {
            File f = files.removeFirst();
            if (f.isDirectory()) {
                File[] subs = f.listFiles();
                if (subs == null) {
                    continue;
                }
                for (File sub : subs) {
                    files.addFirst(sub);
                }
                continue;
            }
            if (!f.getName().toLowerCase().endsWith(fileType)) {
                continue;
            }
            //拿到java
            try {
                String content = new String(Files.readAllBytes(Paths.get(f.getAbsolutePath())));
                //去掉java注解
                content = content.replaceAll(comment, "");
                Pattern pattern = Pattern.compile("\"([^\"]*[\u4e00-\u9fa5]+[^\"]*)\"");
                Matcher matcher = pattern.matcher(content);
                if (matcher.find()) {
                    resultFiles.add(f);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultFiles;
    }
}
